import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { Button, Checkbox } from 'antd';
import CustomMultipleTop from './CustomMultipleTop';
import CategoryListRender from '../CategoryListRender';
import { TextWidget } from '@inbiz/react';
import type { ICategorySelect } from '../content';
import type { ISearchData } from '../../../../designer/service';
export default function CategoryItem({
  item,
  selected,
  onSelected,
  show,
  level,
  IsWhether,
  config,
  parentItem,
  showCustomValue,
  designer
}: {
  item: ISearchData['SectionList'][number];
  selected: string[];
  onSelected: ICategorySelect;
  show: boolean;
  IsWhether: boolean;
  level: number;
  showCustomValue: boolean;
  designer: boolean
}) {
  const [openStatus, $openStatus] = useState(false);
  const [showMore, $showMore] = useState(false);
  const contentRef = useRef()
  // 是否选中全部, 只要选中一个分类，全部就不选中
  const isSelectAll = useMemo(() => {
    let allKeys: string[] = []
    if (item.IsGroup) {
      allKeys = item.SectionGroupData.map(ele => {
        return ele.sectionItemList.map(element => element.Key)
      }).flat()
    } else {
      allKeys = item.sectionItemList.map(element => element.Key)
    }
    return !selected.some((ele) => allKeys.includes(ele));

  }, [selected, item.Key]);
  const handleAllClick = useCallback(
    (e) => {
      if (!isSelectAll) {
        const allKey = item.Key + ':';
        onSelected(
          selected.filter((select) => select.indexOf(allKey) === 0),
          false,
          level,
          IsWhether,
        );
      }
    },
    [isSelectAll, selected, item.Key, onSelected, item],
  );
  const handleResize = () => {
    if (contentRef.current) {
      let operationBoxwidth
      const contentwidth = contentRef.current.clientWidth - 50
      
       /**
       * 当显示二级三级时, 用sectionItemList, 当显示一级二级且不是自定义时, 用sectionItemList
       * 当显示一级二级三级时, 用SctionGroupData, 当显示一级二级且是自定义时,用SectionGroupData
       * ShowHierarchy居然有0的时候
       */
       if (parentItem.ShowHierarchy == 1 || (parentItem.ShowHierarchy == 2 && !parentItem.IsGroup) || (parentItem.ShowHierarchy == 0 && parentItem.sectionItemList)) {
        const sectionlength = item.sectionItemList.length
        operationBoxwidth = 146 * sectionlength
      } else if (parentItem.ShowHierarchy == 3 && parentItem.SectionGroupData) {
        const grouplength = parentItem.SectionGroupData.length
        operationBoxwidth = 146 * grouplength
      }
      // 当有自定义时, 要再加上输入框的长度
      if (parentItem.IsCustomSearch) {
        operationBoxwidth += 330
      }
      $showMore(operationBoxwidth > contentwidth)
    }
  }
  useEffect(() => {
    handleResize()
    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])
  return (
    <ul
      className="categoryBox"
      style={{ height: openStatus ? 'auto' : 32, display: show ? 'flex' : 'none' }}
    >
      <li className="title" title={item.Value}>
        {item.Value}
      </li>
      <li
        className={`allBtn ${!IsWhether && isSelectAll ? 'selected' : ''} ${IsWhether ? 'multipleSelected' : ''
          }`}
      >
        {IsWhether ? (
          <Checkbox checked={isSelectAll} onClick={handleAllClick}>
            <Button size="small" shape="round" key={item.Key} onClick={handleAllClick}>
              <TextWidget>SearchResultEngine.whole</TextWidget>
            </Button>
          </Checkbox>
        ) : (
          <Button size="small" shape="round" key={item.Key} onClick={handleAllClick}>
            <TextWidget>SearchResultEngine.whole</TextWidget>
          </Button>
        )}
      </li>
      <li className="content" ref={contentRef}>
        <div className="operationBox">
          {item.ShowHierarchy == 3 && item.IsGroup ? (
            <CustomMultipleTop
              parentItem={parentItem}
              selected={selected}
              onSelected={onSelected}
              level={level}
              designer={designer}
            />
          ) : (
            <CategoryListRender
              item={item}
              selected={selected}
              onSelected={onSelected}
              level={level}
              IsWhether={IsWhether}
              config={config}
              parentItem={parentItem}
              showCustomValue={showCustomValue}
            />
          )}
          {showMore && <a className="moreBtn" onClick={() => $openStatus(!openStatus)}>
            <TextWidget>
              {openStatus ? 'SearchResultEngine.putAway' : 'SearchResultEngine.more'}
            </TextWidget>
          </a>}
          {/* <div className="mask" /> */}
        </div>
      </li>
    </ul>
  );
}
